package com.banggood.pss.mqtools.bean;


import com.banggood.pps.commons.exception.BusinessException;
import com.banggood.pss.mqtools.util.ChannelCreator;
import com.rabbitmq.client.MessageProperties;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

/**
 * 用于mq的消息发送
 * @author Mr.chen
 * @date 2020/8/14 14:40
 */
public class JsonMessageSender extends MqBaseBean implements InitializingBean, DisposableBean {

    public JsonMessageSender(String queueName) {
        super(queueName);
    }

    public JsonMessageSender(String queueName,String exchange) {
        super(queueName,exchange);
    }

    public JsonMessageSender(String queueName,String exchange,String routingKey) {
        super(queueName,exchange,routingKey);
    }

    public synchronized void sendJsonMessageToQueue(String json) {
        try {
            getChannel().basicPublish("", queueName, null, json.getBytes("UTF-8"));
        } catch (IOException e) {
            logger.info(e.getMessage(),e);
        }
    }

    /**
     * 官方推荐加锁发送消息
     * @param json
     */
    public synchronized void sendJsonMessageToExchange(String json) {
        if(exchangeName == null) {
            throw new BusinessException("exchangeName must not null !!!");
        }
        try {
            getChannel().basicPublish(exchangeName, "", MessageProperties.PERSISTENT_TEXT_PLAIN, json.getBytes("UTF-8"));
        } catch (IOException e) {
            logger.info(e.getMessage(),e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        createQueue();
    }

    @Override
    public void destroy() throws Exception {
        channelCreator.closeConnect();
        ChannelCreator.closeChannel(getChannel());
    }
}
